<?php

namespace App\Http\Controllers;

use App\Http\Requests\TaskRequest;
use App\Models\FsUserTask;
use App\Models\Task;
use App\Transformers\FsUserTransformer;
use App\Transformers\TaskTransformer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class TaskController extends Controller
{
    /**
     * @api {post} /api/task 任务添加
     * @apiGroup Task
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {String} name  任务名
     * @apiParam {int} carry_user_id  执行任务人的id
     * @apiParam {array} ids  会员的id
     * @apiParam {datetime} start_time  任务开始时间
     * @apiParam {datetime} send_time  任务结束
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 201 OK
     */
    public function store(TaskRequest $request, Task $task){
        $data = $request->all();
        $data['create_user_id'] = Auth::user()->id;
        $data['count'] = count($data['ids']);
        $res = DB::transaction(function()use($task, $data)
        {
            $res = $task->create($data);
            $carry_user_id = $data['carry_user_id'];
            foreach($data['ids'] as $k){
                DB::table('fs_user_tasks')->insert([
                    'task_id'=>$res->id,
                    'fs_user_id'=>$k,
                    'carry_user_id'=>$carry_user_id
                ]);
            }
            return true;
        });
        if($res){
            return $this->response->created();
        }else{
            return response()->json(['message'=>'添加失败','status_code'=>200], 200);
        }
    }
    /**
     * @api {patch} /api/task/:id 任务修改
     * @apiGroup Task
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} id  任务id （url传参）
     * @apiParam {String} name  任务名
     * @apiParam {int} carry_user_id  执行任务人的id
     * @apiParam {array} ids  会员的id
     * @apiParam {datetime} start_time  任务开始时间
     * @apiParam {datetime} send_time  任务结束
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 201 OK
     */
    public function update(TaskRequest $request, Task $task){
        $data = $request->all();
        $data['create_user_id'] = Auth::user()->id;
        $data['count'] = count($data['ids']);
        $res = DB::transaction(function()use($task, $data)
        {

            $res = DB::table('tasks')->where('id',$task->id)->update([
                'name'=>$data['name'],
                'carry_user_id' => $data['carry_user_id'],
                'count' => $data['count'],
                'start_time'=> $data['start_time'],
                'end_time' => $data['end_time']
            ]);

            $carry_user_id = $data['carry_user_id'];
            DB::table('fs_user_tasks')->where('task_id',$task->id)->delete();
            foreach($data['ids'] as $k){
                DB::table('fs_user_tasks')->insert([
                    'task_id'=>$task->id,
                    'fs_user_id'=>$k,
                    'carry_user_id'=>$carry_user_id
                ]);
            }
            return true;
        });
        if($res){
            return response()->json(['message' => '修改成功']);
        }else{
            return response()->json(['message'=>'修改失败','status_code'=>200], 200);
        }
    }

    /**
     * @api {get} /api/task?include=createUser,carryUser 任务列表(所有任务)
     * @apiGroup Task
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} limit  一页的数量
     * @apiParam {int} page  第几页
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *           "data": [
     *               {
     *               "id": 6,
     *               "name": "是大大大",
     *               "carry_user_id": 1,
     *               "create_user_id": 1,
     *               "start_time": "2019-01-23 06:36:02",
     *               "end_time": "2019-01-23 06:36:02",
     *               "count": "2-会员人数",
     *               "not_call_count": "1-待回访人数",
     *               "comple_call_count": "1-接通总人数",
     *               "comple_task_rate": "0.5-完成度",
     *               "comple_people_count": "2-接通人数",
     *               "comple_people_rate": "1-接通率",
     *               "created_at": "2019-01-23 14:35:10",
     *               "updated_at": "2019-01-23 14:36:02"
     *               }
     *           ]
     *        }
     */
    public function index(Request $request,Task $task){

        $tasks = $task->orderByDesc('created_at')->paginate($request->get('limit',10));

        return $this->response->paginator($tasks, new TaskTransformer());
    }

    /**
     * @api {get} /api/task/current?include=createUser,carryUser 登陆者的任务列表
     * @apiGroup Task
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} limit  一页的数量
     * @apiParam {int} page  第几页
     * @apiParam {int} select  0未完成 1已完成 3逾期未完成  4逾期完成 5全部
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *           "data": [
     *               {
     *                   "id": 1,
     *                   "name": "qwqw",
     *                   "carry_user_id": 1,
     *                   "create_user_id": 1,
     *                   "start_time": null,
     *                   "end_time": null,
     *                   "created_at": "",
     *                   "updated_at": ""
     *               }
     *           ]
     *        }
     */
    public function currentIndex(Request $request,Task $task){
        $select = $request->input('select',5);
        $carry_user_id = Auth::id();

        if($select == 5){
            $tasks = $task->where('carry_user_id',$carry_user_id)->orderByDesc('created_at')->paginate($request->get('limit',10));
        }else{
            $tasks = $task->where('carry_user_id',$carry_user_id)->where('status',$request->select)->orderByDesc('created_at')->paginate($request->get('limit',10));
        }
        return $this->response->paginator($tasks, new TaskTransformer());
    }

    /**
     * @api {delete} /api/task/:id 任务删除
     * @apiGroup Task
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} id  任务id(url)
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 204 OK
     */
    public function destroy(Task $task){
        $res = DB::transaction(function()use($task)
        {
            DB::table('fs_user_tasks')->where('task_id',$task->id)->delete();
            $task->delete();
            return true;
        });
        return $this->response->noContent();
    }

    /**
     * @api {get} /api/task/:id 任务会员展示
     * @apiGroup Task
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} user 用户id(url中传入，必传参数)
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     */
    public function show(Request $request, Task $task){
        if(!Auth::user()->hasPermissionTo('api.task.index.all')){
            if($task->carry_user_id != Auth::id()){
                return response()->json(['message' => '只能查看自己的任务'],422);
            }
        }
        $tasks = $task->fsUsers()->paginate($request->get('limit',10));
        return $this->response->paginator($tasks, new FsUserTransformer());
    }

    /**
     * @api {delete} /api/remove/task/fsUser  单个解除会员维护关系
     * @apiGroup Task
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} fs_user_id 会员id
     * @apiParam {int} carry_user_id 后台用户id
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     */
    public function removeFsUser(Request $request,FsUserTask $fsUserTask){
        $data = $request->validate([
            'fs_user_id'=>'required|exists:mysql_branch.fs_user,id',
            'carry_user_id' => 'required|exists:users,id',
        ]);
        $fs_user_tasks = $fsUserTask->where([
            ['fs_user_id','=',$data['fs_user_id']],
            ['carry_user_id','=',$data['carry_user_id']]
        ])->get();
        if(empty($fs_user_tasks)){
            return response()->json(['message' => '数据错误'],422);
        }

        foreach($fs_user_tasks as $fs_user_task){
            if(empty($fs_user_task->task_id)){
                //如果是导入的会员直接删
                $fs_user_task->delete();
            }else{
                //如果是任务下的关系，先task表count减1，再删除
                Task::find($fs_user_task->task_id)->decrement('count');
                $fs_user_task->delete();
            }
        }
        return response()->json(['message' => '解绑成功']);
    }

    /**
     * @api {delete} /api/remove/patch/task/fsUser  批量解除会员维护关系
     * @apiGroup Task
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {array} ids 会员id
     * @apiParam {int} carry_user_id 后台用户id
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     */
    public function patchRemoveFsUser(Request $request, FsUserTask $fsUserTask){
        $data = $request->validate([
            'carry_user_id' => 'required|exists:users,id',
            'ids' => 'required|array',
            'ids.*' => 'exists:mysql_branch.fs_user,id',
        ]);
        $fs_user_tasks = $fsUserTask->where('carry_user_id',$data['carry_user_id'])->whereIn('fs_user_id',$data['ids'])->get();
        if($fs_user_tasks){
            foreach($fs_user_tasks as $fs_user_task){
                if(empty($fs_user_task->task_id)){
                    //如果是导入的会员直接删
                    $fs_user_task->delete();
                }else{
                    //如果是任务下的关系，先task表count减1，再删除
                    Task::find($fs_user_task->task_id)->decrement('count');
                    $fs_user_task->delete();
                }
            }
        }
        return response()->json(['message' => '解绑成功']);
    }

    /**
     * @api {delete} /api/remove/all/task/fsUser  一键解除会员维护所有关系
     * @apiGroup Task
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} user_id 后台用户id
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     */
    public function allRemoveFsUser(Request $request){
        $data = $request->validate([
            'user_id' => 'required|exists:users,id',
        ]);
        //删除fs_user_tasks表中的数据
        FsUserTask::where('carry_user_id',$data['user_id'])->delete();
        //任务的人数清零
        Task::where('carry_user_id',$data['user_id'])->update(['count'=>0]);

        return response()->json(['message' => '解绑成功']);
    }
}
